<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能驾驶辅助系统</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome图标 -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <script>
        // 配置Tailwind自定义颜色
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        success: '#00B42A',
                        dark: '#1D2129',
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .video-container {
                @apply relative w-full bg-gray-900 rounded-lg overflow-hidden;
            }
            .status-indicator {
                @apply absolute top-2 right-2 w-3 h-3 rounded-full;
            }
            .control-btn {
                @apply px-4 py-2 rounded-md text-white font-medium transition-all duration-200;
            }
            .debug-panel {
                @apply bg-gray-800 text-white p-2 rounded text-xs max-h-24 overflow-y-auto;
            }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-6 max-w-7xl">
        <!-- 标题区域 -->
        <header class="mb-6">
            <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-dark">智能驾驶辅助系统</h1>
            <p class="text-gray-600">实时监测路况与驾驶行为，保障行车安全</p>
        </header>

        <!-- 主内容区域 -->
        <main>
            <!-- 视频监控区域 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
                <!-- 前方车辆检测视频 -->
                <div class="video-container">
                    <h2 class="text-white bg-primary px-4 py-2">
                        <i class="fa fa-car mr-2"></i>前方车辆监测
                    </h2>
                    <div class="aspect-video flex items-center justify-center">
                        <canvas id="vehicleCanvas" class="w-full h-full object-cover bg-black"></canvas>
                        <!-- 加载状态 -->
                        <div id="vehicleLoading" class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-50">
                            <div class="text-white text-xl">
                                <i class="fa fa-circle-o-notch fa-spin mr-2"></i>加载中...
                            </div>
                        </div>
                    </div>
                    <!-- 状态指示器 -->
                    <div id="vehicleStatus" class="status-indicator bg-gray-500"></div>
                    <!-- 车辆信息面板 -->
                    <div class="bg-gray-800 text-white p-3 text-sm">
                        <div class="grid grid-cols-2 gap-2">
                            <div>
                                <span class="text-gray-400">车辆数量:</span>
                                <span id="vehicleCount" class="font-medium">0</span>
                            </div>
                            <div>
                                <span class="text-gray-400">最近距离:</span>
                                <span id="closestDistance" class="font-medium">-- m</span>
                            </div>
                        </div>
                        <div id="vehicleWarning" class="mt-1 text-danger hidden">
                            <i class="fa fa-exclamation-triangle mr-1"></i>
                            <span>前方车辆过近，请谨慎驾驶！</span>
                        </div>
                    </div>
                    <!-- 调试信息 -->
                    <div class="debug-panel">
                        <div>车辆检测状态: <span id="vehicleDebug">等待数据...</span></div>
                    </div>
                </div>

                <!-- 驾驶员行为识别视频 -->
                <div class="video-container">
                    <h2 class="text-white bg-primary px-4 py-2">
                        <i class="fa fa-user mr-2"></i>驾驶员行为监测
                    </h2>
                    <div class="aspect-video flex items-center justify-center">
                        <canvas id="driverCanvas" class="w-full h-full object-cover bg-black"></canvas>
                        <!-- 加载状态 -->
                        <div id="driverLoading" class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-50">
                            <div class="text-white text-xl">
                                <i class="fa fa-circle-o-notch fa-spin mr-2"></i>加载中...
                            </div>
                        </div>
                    </div>
                    <!-- 状态指示器 -->
                    <div id="driverStatus" class="status-indicator bg-gray-500"></div>
                    <!-- 行为信息面板 -->
                    <div class="bg-gray-800 text-white p-3 text-sm">
                        <div>
                            <span class="text-gray-400">当前状态:</span>
                            <span id="driverStatusText" class="font-medium">未监测</span>
                        </div>
                        <div id="behaviorWarning" class="mt-1 text-danger hidden">
                            <i class="fa fa-exclamation-triangle mr-1"></i>
                            <span id="warningMessage"></span>
                        </div>
                    </div>
                    <!-- 调试信息 -->
                    <div class="debug-panel">
                        <div>驾驶员检测状态: <span id="driverDebug">等待数据...</span></div>
                    </div>
                </div>
            </div>

            <!-- 系统控制区域 -->
            <div class="bg-white rounded-lg shadow p-6 mb-8">
                <h2 class="text-xl font-semibold mb-4 text-dark">
                    <i class="fa fa-cogs mr-2"></i>系统控制
                </h2>

                <div class="flex flex-wrap gap-4 mb-6">
                    <button id="startBtn" class="control-btn bg-success hover:bg-success/80">
                        <i class="fa fa-play mr-1"></i>启动系统
                    </button>
                    <button id="stopBtn" class="control-btn bg-danger hover:bg-danger/80" disabled>
                        <i class="fa fa-stop mr-1"></i>停止系统
                    </button>
                    <button id="resetBtn" class="control-btn bg-warning hover:bg-warning/80" disabled>
                        <i class="fa fa-refresh mr-1"></i>重置系统
                    </button>
                    <button id="detectBtn" class="control-btn bg-primary hover:bg-primary/80">
                        <i class="fa fa-search mr-1"></i>检测摄像头
                    </button>
                </div>

                <!-- 系统设置 -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <h3 class="font-medium mb-2 text-dark">车辆检测设置</h3>
                        <div class="mb-3">
                            <label class="block text-sm text-gray-600 mb-1">预警距离阈值 (米)</label>
                            <input type="number" id="distanceThreshold"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md"
                                   value="30" min="5" max="100">
                        </div>
                        <div class="mb-3">
                            <label class="block text-sm text-gray-600 mb-1">车辆摄像头索引</label>
                            <select id="vehicleCamIndex" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                                <option value="0">0</option>
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                            </select>
                        </div>
                    </div>

                    <div>
                        <h3 class="font-medium mb-2 text-dark">行为识别设置</h3>
                        <div class="mb-3">
                            <label class="block text-sm text-gray-600 mb-1">连续检测帧数阈值</label>
                            <input type="number" id="frameThreshold"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md"
                                   value="15" min="5" max="50">
                        </div>
                        <div class="mb-3">
                            <label class="block text-sm text-gray-600 mb-1">驾驶员摄像头索引</label>
                            <select id="driverCamIndex" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                                <option value="0">0</option>
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 系统日志区域 -->
            <div class="bg-white rounded-lg shadow p-6">
                <h2 class="text-xl font-semibold mb-4 text-dark">
                    <i class="fa fa-history mr-2"></i>系统日志
                </h2>
                <div id="systemLog" class="border border-gray-200 rounded-md h-40 overflow-y-auto p-3 text-sm bg-gray-50">
                    <div class="text-gray-500">系统未启动</div>
                </div>
            </div>
        </main>

        <!-- 页脚 -->
        <footer class="mt-8 text-center text-gray-500 text-sm py-4">
            智能驾驶辅助系统 &copy; 2023
        </footer>
    </div>

    <script>
        // 全局变量
        let socket;
        let isRunning = false;
        let vehicleFrameCount = 0;
        let driverFrameCount = 0;
        let lastVehicleFrameTime = 0;
        let lastDriverFrameTime = 0;
        let frameInterval = 100; // 帧间隔时间（毫秒）

        // DOM元素
        const startBtn = document.getElementById('startBtn');
        const stopBtn = document.getElementById('stopBtn');
        const resetBtn = document.getElementById('resetBtn');
        const detectBtn = document.getElementById('detectBtn');
        const distanceThreshold = document.getElementById('distanceThreshold');
        const frameThreshold = document.getElementById('frameThreshold');
        const vehicleCamIndex = document.getElementById('vehicleCamIndex');
        const driverCamIndex = document.getElementById('driverCamIndex');
        const systemLog = document.getElementById('systemLog');

        // Canvas相关元素
        const vehicleCanvas = document.getElementById('vehicleCanvas');
        const vehicleCtx = vehicleCanvas.getContext('2d');
        const driverCanvas = document.getElementById('driverCanvas');
        const driverCtx = driverCanvas.getContext('2d');
        const vehicleLoading = document.getElementById('vehicleLoading');
        const driverLoading = document.getElementById('driverLoading');
        const vehicleStatus = document.getElementById('vehicleStatus');
        const driverStatus = document.getElementById('driverStatus');

        // 状态显示元素
        const vehicleCount = document.getElementById('vehicleCount');
        const closestDistance = document.getElementById('closestDistance');
        const vehicleWarning = document.getElementById('vehicleWarning');
        const driverStatusText = document.getElementById('driverStatusText');
        const behaviorWarning = document.getElementById('behaviorWarning');
        const warningMessage = document.getElementById('warningMessage');

        // 调试元素
        const vehicleDebug = document.getElementById('vehicleDebug');
        const driverDebug = document.getElementById('driverDebug');

        // 设置Canvas尺寸
        function resizeCanvas(canvas, width, height) {
            canvas.width = width;
            canvas.height = height;
        }

        // 初始化Canvas尺寸
        resizeCanvas(vehicleCanvas, 640, 480);
        resizeCanvas(driverCanvas, 640, 480);

        // 添加日志
        function addLog(message, isError = false) {
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.className = isError ? 'text-danger' : '';
            logEntry.innerHTML = `<span class="text-gray-500">[${timestamp}]</span> ${message}`;
            systemLog.appendChild(logEntry);
            systemLog.scrollTop = systemLog.scrollHeight; // 滚动到底部
        }

        // 更新车辆检测信息
        function updateVehicleInfo(data) {
            vehicleCount.textContent = data.vehicle_count;

            // 处理可能的 null 值或大数值
            let distanceText = '--';
            if (data.closest_distance !== null && data.closest_distance < 9999) {
                distanceText = data.closest_distance.toFixed(1) + ' m';
            }
            closestDistance.textContent = distanceText;

            // 更新预警状态
            if (data.warning) {
                vehicleWarning.classList.remove('hidden');
                vehicleStatus.className = 'status-indicator bg-danger';
            } else {
                vehicleWarning.classList.add('hidden');
                vehicleStatus.className = 'status-indicator bg-success';
            }

            // 更新视频流
            if (data.frame) {
                const img = new Image();
                img.onload = function() {
                    // 调整Canvas尺寸以适应图像
                    resizeCanvas(vehicleCanvas, img.width, img.height);
                    vehicleCtx.clearRect(0, 0, vehicleCanvas.width, vehicleCanvas.height);
                    vehicleCtx.drawImage(img, 0, 0);
                    vehicleLoading.classList.add('hidden');

                    // 更新调试信息
                    vehicleFrameCount++;
                    const now = Date.now();
                    const fps = now - lastVehicleFrameTime > 0 ?
                        Math.round(1000 / (now - lastVehicleFrameTime)) : 0;
                    lastVehicleFrameTime = now;
                    vehicleDebug.textContent = `帧数: ${vehicleFrameCount} | FPS: ${fps}`;
                };
                img.onerror = function() {
                    addLog('车辆帧图像加载失败', true);
                    vehicleDebug.textContent = '图像加载失败';
                };
                img.src = `data:image/jpeg;base64,${data.frame}`;
            } else {
                vehicleDebug.textContent = '未收到帧数据';
                vehicleLoading.classList.remove('hidden');
            }
        }

        // 更新驾驶员行为信息
        function updateDriverInfo(data) {
            // 查找当前行为
            let currentBehavior = '正常驾驶';
            let warningText = '';

            for (const [behavior, detected] of Object.entries(data.behaviors)) {
                if (detected && behavior !== 'normal') {
                    currentBehavior = getBehaviorText(behavior);
                    warningText = `检测到${currentBehavior}，请安全驾驶！`;
                    break;
                }
            }

            driverStatusText.textContent = currentBehavior;

            // 更新预警状态
            if (warningText) {
                behaviorWarning.classList.remove('hidden');
                warningMessage.textContent = warningText;
                driverStatus.className = 'status-indicator bg-danger';
            } else {
                behaviorWarning.classList.add('hidden');
                driverStatus.className = 'status-indicator bg-success';
            }

            // 更新视频流
            if (data.frame) {
                const img = new Image();
                img.onload = function() {
                    // 调整Canvas尺寸以适应图像
                    resizeCanvas(driverCanvas, img.width, img.height);
                    driverCtx.clearRect(0, 0, driverCanvas.width, driverCanvas.height);
                    driverCtx.drawImage(img, 0, 0);
                    driverLoading.classList.add('hidden');

                    // 更新调试信息
                    driverFrameCount++;
                    const now = Date.now();
                    const fps = now - lastDriverFrameTime > 0 ?
                        Math.round(1000 / (now - lastDriverFrameTime)) : 0;
                    lastDriverFrameTime = now;
                    driverDebug.textContent = `帧数: ${driverFrameCount} | FPS: ${fps}`;
                };
                img.onerror = function() {
                    addLog('驾驶员帧图像加载失败', true);
                    driverDebug.textContent = '图像加载失败';
                };
                img.src = `data:image/jpeg;base64,${data.frame}`;
            } else {
                driverDebug.textContent = '未收到帧数据';
                driverLoading.classList.remove('hidden');
            }
        }

        // 行为文本映射
        function getBehaviorText(behavior) {
            const behaviorMap = {
                'smoking': '抽烟行为',
                'drinking': '喝水行为',
                'phone': '使用手机',
                'calling': '打电话'
            };
            return behaviorMap[behavior] || behavior;
        }

        // 连接WebSocket
        function connectWebSocket() {
            // 注意：实际部署时需要替换为正确的WebSocket地址
            const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${wsProtocol}//${window.location.host}/ws`;

            // 本地开发时使用固定地址
            const devUrl = "ws://localhost:8000/ws";
            const useDev = window.location.hostname === 'localhost' ||
                           window.location.hostname === '127.0.0.1';

            socket = new WebSocket(useDev ? devUrl : wsUrl);

            socket.onopen = function() {
                addLog('已连接到服务器');
                startBtn.disabled = false;
                detectBtn.disabled = false;
            };

            socket.onmessage = function(event) {
                try {
                    const data = JSON.parse(event.data);

                    if (data.type === 'vehicle') {
                        updateVehicleInfo(data);
                    } else if (data.type === 'driver') {
                        updateDriverInfo(data);
                    } else if (data.type === 'log') {
                        addLog(data.message, data.is_error);
                    } else if (data.type === 'camera_list') {
                        updateCameraList(data.available_cameras);
                    }
                } catch (e) {
                    addLog(`消息解析错误: ${e.message}`, true);
                }
            };

            socket.onerror = function(error) {
                addLog(`WebSocket错误: ${error.message || '未知错误'}`, true);
            };

            socket.onclose = function(event) {
                addLog(`连接关闭: ${event.reason || event.code}`, true);
                vehicleStatus.className = 'status-indicator bg-gray-500';
                driverStatus.className = 'status-indicator bg-gray-500';

                if (isRunning) {
                    addLog('尝试重新连接...');
                    setTimeout(connectWebSocket, 3000);
                } else {
                    startBtn.disabled = false;
                    stopBtn.disabled = true;
                    resetBtn.disabled = true;
                    detectBtn.disabled = false;
                }
            };
        }

        // 更新摄像头列表
        function updateCameraList(cameras) {
            // 清空选项
            vehicleCamIndex.innerHTML = '';
            driverCamIndex.innerHTML = '';

            // 添加检测到的摄像头
            cameras.forEach(cam => {
                const option = document.createElement('option');
                option.value = cam;
                option.textContent = cam;
                vehicleCamIndex.appendChild(option.cloneNode(true));
                driverCamIndex.appendChild(option);
            });

            addLog(`检测到可用摄像头: ${cameras.join(', ')}`);
        }

        // 发送控制命令
        function sendCommand(command, params = {}) {
            if (socket && socket.readyState === WebSocket.OPEN) {
                const message = {
                    command: command,
                    params: params
                };
                socket.send(JSON.stringify(message));
                addLog(`发送命令: ${command}`);
            } else {
                addLog('未连接到服务器，无法发送命令', true);
            }
        }

        // 事件监听器
        startBtn.addEventListener('click', function() {
            // 获取阈值设置
            const distanceThresh = parseInt(distanceThreshold.value);
            const frameThresh = parseInt(frameThreshold.value);
            const vehicleCam = parseInt(vehicleCamIndex.value);
            const driverCam = parseInt(driverCamIndex.value);

            // 发送启动命令
            sendCommand('start', {
                distance_threshold: distanceThresh,
                frame_threshold: frameThresh,
                vehicle_camera_index: vehicleCam,
                driver_camera_index: driverCam
            });

            isRunning = true;
            startBtn.disabled = true;
            stopBtn.disabled = false;
            resetBtn.disabled = false;
            detectBtn.disabled = true;
            distanceThreshold.disabled = true;
            frameThreshold.disabled = true;
            vehicleCamIndex.disabled = true;
            driverCamIndex.disabled = true;

            addLog('启动系统...');

            // 显示加载状态
            vehicleLoading.classList.remove('hidden');
            driverLoading.classList.remove('hidden');
        });

        stopBtn.addEventListener('click', function() {
            sendCommand('stop');
            isRunning = false;
            startBtn.disabled = false;
            stopBtn.disabled = true;
            detectBtn.disabled = false;
            distanceThreshold.disabled = false;
            frameThreshold.disabled = false;
            vehicleCamIndex.disabled = false;
            driverCamIndex.disabled = false;

            vehicleStatus.className = 'status-indicator bg-gray-500';
            driverStatus.className = 'status-indicator bg-gray-500';
            vehicleWarning.classList.add('hidden');
            behaviorWarning.classList.add('hidden');

            addLog('停止系统');
        });

        resetBtn.addEventListener('click', function() {
            sendCommand('reset');
            addLog('重置系统');
        });

        detectBtn.addEventListener('click', function() {
            sendCommand('detect_cameras');
            addLog('检测摄像头...');
        });

        // 初始化连接
        window.addEventListener('load', function() {
            addLog('页面加载完成，正在连接服务器...');
            connectWebSocket();
        });

        // 页面关闭时断开连接
        window.addEventListener('beforeunload', function() {
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.close();
            }
        });

        // 帧率监控
        setInterval(() => {
            const now = Date.now();
            const vehicleFps = now - lastVehicleFrameTime > 2000 ? 0 :
                Math.round(1000 / frameInterval);
            const driverFps = now - lastDriverFrameTime > 2000 ? 0 :
                Math.round(1000 / frameInterval);

            if (isRunning) {
                if (vehicleFps === 0) {
                    vehicleDebug.textContent = '无数据流';
                    vehicleLoading.classList.remove('hidden');
                }
                if (driverFps === 0) {
                    driverDebug.textContent = '无数据流';
                    driverLoading.classList.remove('hidden');
                }
            }
        }, 1000);
    </script>
</body>
</html>